<template>
  <div v-show="IfVisible" style="width: 100%" tabIndex="-1">
    <FilterPanel  :selectHelperSearchConfig="selectHelperSearchConfig" :isShowTopContent="isShowTopContent"
      :operatePosition="operatePosition" ref="filters_panel" v-model:Groups="FilterGroups"
      @update:Group="({ index, value }) => (FilterGroups[index] = value)" @update:GroupChild="({ GroupIndex, index, value }) =>
          (FilterGroups[GroupIndex].Children[index] = value)
        " :quckFilterValue="quckFilterValue" :enableQuickFilter="enableQuickFilter" :staticItems="staticItems"
      v-model:ValuesGroups="ValuesGroups" v-model:Fields="FieldsConfig" v-model:FiltersIsShow="FiltersIsShow"
      :IniLoadedFiltersIsShow="IniLoadedFiltersIsShow" v-model:IsAuto="ChangeAutoRun"
      v-model:FilterIsEasy="FilterIsEasy" v-model:FilterIsClassic="FilterIsClassic"
      v-model:FilterIsChange="FilterIsChange" :showShortcutCondition="showShortcutCondition" :tabIndex="tabIndex"
      :Mappings="DataMappings" :Conditions="DataConditions" :InitValueScript="this.GetInitValueByScript"
      :PageID="pageID" :PageCode="pageCode" :filterFields_QuickFilter="filterFields_QuickFilter"
      :filterFields="filterFields" :PlanID="FilterPlanID" @querySummary="querySummary"
      @fasr_quick_filter_Init='fasr_quick_filter_Init' :isShowCollapse="isShowCollapse"   :fasr_filter_QuickItemSummary="quickItemSummary"
    :fasr_filter_QuickItems="quickItems" :isShowOperateCellButton="isShowOperateCellButton">
    </FilterPanel>
  </div>
</template>

<script>
import { ref } from 'vue';
import { useQuasar } from '@teld/q-components';
import _ from 'lodash';
import { commonProps } from 't/common/utils';
import FilterPanel from './FilterPanel';
import _dataConditions from './config/constConditions';
import _filterFields from './config/constFields';
import _dataMappings from './config/constMappings';
import _timeTerms from './config/constTimeTerms';
import _timeVar from './config/constTimeVar';
import { Terms, getI18nTerms, getTextByCode } from './config/resouce';
import { FilterExpression } from '../query-plan/covert';

const Funcs = window.Funcs || {
  Notify: () => { },
  GetTerms: (c, n) => n,
  AtVarTransform: () => { },
  FasRequestTagAdd: () => { },
  Confirm: () => { },
  DateTimeToString: () => { },
  DateToString: () => { },
};

// 是否设计时
const inDesign = !!window['fas']?.inDesign || !window.readCookie;

export default {
  name: 't-filter',

  props: {
    ...commonProps,

    // 数据模型
    filterService: {
      type: Object,
      default: {
        ServiceID: '',
        ServiceCode: '',
        ServiceType: '',
        ActionType: 3,
      },
    },
    // 筛选字段
    filterFields: {
      type: Array,
      default: () => [],
    },
    filterFields_QuickFilter: {
      type: Array,
      default: () => [],
    },
    pageID: {
      type: String,
      default: '',
    },
    pageCode: {
      type: String,
      default: '',
    },
    // 是否可见
    visible: {
      type: Boolean,
      default: true,
    },

    // 变更执行
    changeAutoRun: {
      type: Boolean,
      default: false,
    },

    // 默认经典
    isClassic: {
      type: Boolean,
      default: true,
    },

    // 查询条件
    filterExpression: {
      type: String,
      default: '{ "ElementType": "Group", "Filters": [] }',
    },
    // 查询方案
    filterCurrScheme: {
      type: String,
      default: '{ "ElementType": "Group", "Filters": [] }',
    },

    // 筛选方案
    filterScheme: {
      type: Object,
      default: { ElementType: 'Group', Filters: [] },
    },

    associationScheme: Object,

    // 默认经典
    tabIndex: {
      type: String,
      default: '0',
    },
    showShortcutCondition: {
      type: String,
      default: '0',
    },
    staticItems: Array,
    enableQuickFilter: {
      type: Boolean,
      default: '0',
    },
    isCollapse: {
      type: Boolean,
      default: '1',
    },
    
    isShowCollapse:{
  type: String,
  default: '1',
},
    isShowTopContent: {
      type: Boolean,
      default: '1',
    },
    operatePosition: {
      type: String,
      default: '1',
    },
    selectHelperSearchConfig: {
      type: Object,
      default: '0',
    },
    quickItems:{
      type: Array,
      default: () => [],
    },
    quickItemSummary:{
      type: Array,
      default: () => [],
    },
    isShowOperateCellButton:{
        type: String,
        default: '1',
    }
  },
  // { label: "默认跟随", value: '1' },
  // { label: "固定位置", value: '0' },
  data() {
    return {
      //国际化
      Term: Terms,
      //筛选条件组，根据查询方案转换
      FilterGroups: [],
      //有值的筛选条件组，三种模式中转组
      ValuesGroups: [],
      //操作模式
      FilterIsEasy: true,
      //是否经典模式
      FilterIsClassic: false,
      //经典模式下是否显示条件
      FiltersIsShow: false,
      IniLoadedFiltersIsShow: false, //初始化获取配置
      //是否发生变化
      FilterIsChange: false,
      //初始方案
      InitGroups: [],
      //筛选字段
      FieldsConfig: [],
      //数据类型映射
      DataMappings: _dataMappings,
      //条件字典
      DataConditions: _dataConditions,
      //查询方案实例
      AdvQueryInstances: null,
      //是否初始化
      FilterIsInit: true,
      //页面内码
      FilterPageID: !!window.pageMetaData ? window.pageMetaData.ID : '',
      //方案内码
      FilterPlanID: '',
      //
      termList: [],
      // 是否终止应用
      isStopApply: false,
      ChangeAutoRun: this.changeAutoRun,
      FilterScheme: this.filterScheme,
      FilterFields: this.filterFields,
      FilterExpression: this.filterExpression,
      quckFilterValue: {}
    };
  },

  components: {
    FilterPanel,
  },

  watch: {
    computedStatus(val){
      if (inDesign) return
      this.FiltersIsShow = val
      this.IniLoadedFiltersIsShow = true;
    },
    isCollapse(val) {
      //设计器所见所得，运行时不允许修改
      if (!inDesign) {
        return
      }

      this.FiltersIsShow = val === '1' || (this.enableQuickFilter === '0' && this.isShowTopContent === '0');
      this.setMockDataByDesign()
    },
    isShowTopContent(val) {
      //设计器所见所得，运行时不允许修改
      if (!inDesign) {
        return
      }
      this.FiltersIsShow = this.isCollapse === '1' || (this.enableQuickFilter === '0' && this.isShowTopContent === '0');
      this.setMockDataByDesign()
    },
    enableQuickFilter(val) {
      //设计器所见所得，运行时不允许修改
      if (!inDesign) {
        return
      }
      this.FiltersIsShow = this.isCollapse === '1' || (this.enableQuickFilter === '0' && this.isShowTopContent === '0');
      this.setMockDataByDesign()
    },

    isClassic: {
      handler(newValue, oldValue) {
        if (!inDesign) {
          return
        }
        this.FilterIsClassic = !!newValue;
        if (!!newValue) {
          this.$nextTick(() => {
            if (this.isCollapse === '0' && this.isShowTopContent === '1') {
              this.FiltersIsShow = false;
            } else {
              this.FiltersIsShow = true;
            }
            this.setMockDataByDesign()
          })

        }
      },

      immediate: true,

    },
    //筛选条件组
    FilterGroups: {
      handler(newValue, oldValue) {
        //查询方案数据结构
        this.FilterScheme = this.getFilterScheme();
        this.FilterExpression = this.getFilterExpression();
        //有值的筛选条件
        this.ValuesGroups = this.getValuesGroups();
        // alert('========== FilterGroups1');
        //判断是否发生变化
        if (JSON.stringify(newValue) != JSON.stringify(this.InitGroups)) {
          this.FilterIsChange = true;
          this.FilterChange();
          // alert('========== FilterGroups2');
          // 是否处理依赖关系
          window['Fas_FilterIsDealDepend'] = true;
        } else {
          this.FilterIsChange = false;
        }

        // if (!this.FilterIsInit)
        // {
        //   this.FilterChange();
        // }
        if (oldValue.length == 0 && this.FilterIsInit) {
          this.FilterIsInit = false;
          this.FilterIsChange = false;
        }
      },
      deep: true,
    },
    //字段配置,运行时设置
    filterFields: {
      handler(newValue, oldValue) {

        //设计时已经指定，不再接受
        if (
          !inDesign
        ) {
          this.init()

          return;
        }
        this.setMockDataByDesign()

      },
      deep: true,
      immediate: true
    },
    visible(val, oldVal) {
      if (val != oldVal) {
        this.IfVisible.value = val;
      }
    },
  },

  computed: {
 
    computedStatus(){
      return  this.isCollapse === '1' || (this.enableQuickFilter === '0' && this.isShowTopContent === '0');
    },
    quckFilterInstance() {
      if (this.$refs.filters_panel?.FilterIsClassic) {

        return this.$refs.filters_panel.$refs.fasr_quick_filter;
      }
      return null
    },
    //运行时 查询方案、查询条件
    isMobile() {
      return window.TFF?.common?.cts?.isMobile();
    },
  },

  async created() {
    this.termList = await getI18nTerms([
      'Schema.Controls.fas_filter.Terms.date.today',
    ]);
  },

  setup(props, { expose }) {
    const { dialog } = useQuasar();
    const IfVisible = ref(props.visible);
    const checkMust = ref()
    expose({
      visible: IfVisible,
      checkMust
    });
    return {
      notify({ message = '', type = 'info', caption = '' }) {
        Funcs.Notify(caption, message, type);
      },
      dialog,
      IfVisible,
      checkMust
    };
  },

  mounted() {
    if (!window.TeldWebConfig) return
    // if (this.isCollapse === '0') {
    //   this.FiltersIsShow = false;
    // }

    // this.$emit('init')

    // &&this.FilterCheckInput()
    window['Fas_FilterCurr'] = this;
    this.checkMust = () => { 
      if(this.FilterIsClassic){
        return this.FilterCheckMust()
     }else{
       return this.FilterCheckMust()&&this.FilterCheckInput()
     }
    }

  },

  methods: {
    getPageID() {
      return this.pageID ||  window.location.pathname.split('/').pop().split('.')[0]
    },
    init(){

    // 延时是因为低代码出码也是延时处理的，只能如此
    // setTimeout(() => {
    // this.FilterIsClassic = !!this.isClassic && !inDesign;
    const { filterFields } = this;
    // if(this.FieldsConfig.length==0){
    if (!!filterFields && filterFields instanceof Array && !inDesign) {
      this.FieldsConfig = filterFields
        .filter(v => v.isQuery)
        .map(item => ({
          ...item,
          //条件名称转换 国际化
          fieldName:
            Funcs.GetTerms(
              item?.ValueInfo_fieldName?.ReferenceExpr,
              item.fieldName,
            ) || item.fieldName,
        }));
      //  this.FieldsConfig = this.getFilterFieldsByProp(filterFields);
      //  this.filterFields = filterFields;
    } else {
      this.FieldsConfig = this.filterFields && this.filterFields.length ? this.filterFields : _filterFields;
      // this.filterFields = _filterFields;
    }
    // }

    //初始化，兼容设计时
    this.FilterGroups = [];
    this.FilterIsEasy = true;
    //初始化？？？不能注释，注释掉初始化出不来，需要延时处理
     this.setFilters({ ElementType: 'Group', Filters: [] },null,true);
    //}, 50);
      setTimeout(()=>{
        this.IniLoadedFiltersIsShow = true;
      },50)
    },
    getAdvanceFilter() {
      if (this.enableQuickFilter === '1') {

        return this.quckFilterInstance?.getQuickFilter(this.getConvertedFilterExpression())
      } else {
        return this.getConvertedFilterExpression()
      }
    },
    // getFasDynamicFilter(filters) {
    //   if(this.enableQuickFilter==='1'){
    //     return this.quckFilterInstance?.getFasDynamicFilter(this.getConvertedFilterExpression())
    //   }else{
    //     return this.getConvertedFilterExpression()
    //   }
    // },
    setMockDataByDesign() {

      this.FieldsConfig = [];
      this.FieldsConfig = this.filterFields && this.filterFields.length ? this.filterFields : _filterFields;
      this.setFilters({ ElementType: 'Group', Filters: [] });
      this.IniLoadedFiltersIsShow = true;
    },
    getGroupByFilter(e) {
      //改造，传入当前条件
      return this.quckFilterInstance?.getGroupByFilter(this.quckFilterInstance?.getQuickFilter(e || this.getConvertedFilterExpression()))
    },
    zipFasDynamicFilter(o, Filters) {
      if (!Filters) Filters = '{"ElementType":"Group","Filters":[]}'
      if (!o) o = {};
      let _Filters = Filters.push ? Filters : [JSON.parse(Filters)];
      _.transform(
        _Filters,
        (r, v) => {
          if (v.ElementType == 'Filter') {
            r[_.last(v.Code.split('.'))] = v.Value;
          } else if (v.ElementType == 'Group') {
            this.zipFasDynamicFilter(o, v.Filters);
          }
        },
        o,
      );
      return o;
    },
    getFasDynamicFilter(filters) {
      if (this.enableQuickFilter === '1') {

        return this.quckFilterInstance?.getFasDynamicFilter(filters || this.getConvertedFilterExpression())
      }
      let qf = this.zipFasDynamicFilter(null,filters);
      return qf

    },
    getSummaryFields() {
      let groupColumns = this.filterFields_QuickFilter
        ?.filter(f => f.enableStatistics)
        ?.map(item => {
          return {
            Code: `${item.tableCode}.${item.fieldCode}`,
          };
        });
      let groupFields = [];
      let ExtSetting = {
        GroupColumns: groupColumns || [],
      }
      if (ExtSetting && ExtSetting.GroupColumns) {
        groupFields = _.map(ExtSetting.GroupColumns, item =>
          _.last(item.Code.split('.')),
        );
      }
      return groupFields.join();
    },
    fasr_quick_filter_Init() {
      this.$emit("init")
    },
    statisticalQuery() {
      this.$emit('querySummary');
    },
    querySummary() {
      this.$emit('querySummary');
    },
    // 得到国际化处理后的字段配置
    getFilterFieldsByProp(srcFields = []) {
      console.log('================== getFilterFieldsByProp', srcFields);
      return srcFields
        .filter(v => v.isQuery)
        .map(item => {
          return {
            filter_classicConfig: {
              ColNum: 6,
              IsCommUse: true,
              InitValue: '',
              DependCodes: [],
              IsCompDepend: false,
            },

            ...item,
            //条件名称转换 国际化
            fieldName:
              Funcs.GetTerms(
                item?.ValueInfo_fieldName?.ReferenceExpr,
                item.fieldName,
              ) || item.fieldName,

            dataType: !!item.dataTypeOriginal
              ? _.toLower(item.dataTypeOriginal)
              : item.dataType,
            filter_inputWay: this.getInputWay(
              !!item.dataTypeOriginal ? item.dataTypeOriginal : item.dataType,
            ),
            filter_isMust: item.filter_isMust ?? '',
            filter_dataType:
              item.dataType == 'Boolean' ? 'fixed' : item.filter_dataType ?? '',
            filter_dataValue:
              item.dataType == 'Boolean'
                ? '1:是,0:否'
                : item.filter_dataValue ?? '',
            field_condition: item.field_condition ?? '',
          };
        });
    },
    getGuid() {
      function t() {
        return ((65536 * (1 + Math.random())) | 0).toString(16).substring(1);
      }
      return (
        t() + t() + '-' + t() + '-' + t() + '-' + t() + '-' + t() + t() + t()
      );
    },
    getInputWay(dataType) {
      dataType = _.toLower(dataType);
      if (dataType == 'time') {
        return 'time';
      }
      if (dataType == 'date') {
        return 'date';
      }
      if (dataType == 'datetime') {
        return 'time';
      }
      if (dataType == 'timestamp') {
        return 'time';
      }
      if (dataType == 'boolean') {
        return 'down';
      }

      return 'text';
    },
    RegisterAdvQueryInstances(advQueryWidget) {
      this.AdvQueryInstances = advQueryWidget;
    },
    //Scheme换为Groups，仅用作兼容历史数据
    getFitlterGroups(groups, filters, relation) {
      // console.log('======getFitlterGroups======', groups);
      filters.forEach(filter => {
        if (filter.ElementType == 'Filter') {
          let _groupValue = this.getSchemeToGroupValue(
            filter.DataType,
            filter.Value,
            filter.Condition,
            filter.ValueName,
            filter.ValueType,
          );
          groups.push({
            ID: this.getGuid(),
            Type: 'Filter',
            Relation: !!relation ? relation : 'and',
            Code: filter.Code,
            Name: this.fixedName(filter.Code)
              ? this.fixedName(filter.Code)
              : filter.Name,
            Condition:
              filter['ValueType'] == 1
                ? `[${filter.Condition}]`
                : filter.Value === null
                  ? filter.Condition == '='
                    ? 'isblank'
                    : 'isnotblank'
                  : filter.Condition,
            Value:
              filter.Condition != 'between'
                ? !Reflect.has(filter, 'ValueType') || filter.ValueType == 0
                  ? _groupValue
                  : Reflect.has(filter, 'ValueName')
                    ? this.fixedName(_groupValue)
                      ? this.fixedName(_groupValue)
                      : filter.ValueName
                    : _groupValue
                : this.getBetweenGroupValue(filter.ValueName),
            DataType: filter.DataType,
            ValueName:
              filter.Condition != 'between'
                ? !Reflect.has(filter, 'ValueType') || filter.ValueType == 0
                  ? filter.Value
                  : _groupValue
                : this.getBetweenGroupValue(filter.ValueName),
            ValueType: Reflect.has(filter, 'ValueType') ? filter.ValueType : 0,
            IsOff: false,
            Children: [],
          });
        } else if (filter.ElementType == 'Relation') {
          relation = filter.Relation;
        } else {
          var _group = {
            ID: this.getGuid(),
            Type: 'Group',
            Relation: !!relation ? relation : 'and',
            Code: '',
            Name: '',
            Condition: '',
            Value: '',
            DataType: '',
            ValueName: '',
            ValueType: 0,
            IsOff: false,
            Children: [],
          };
          groups.push(_group);
          this.getFitlterGroups(_group.Children, filter.Filters, null);
        }
      });
    },
    getRelactionNodeConfig(fieldAlias) {
      return this.FieldsConfig.filter(
        item => item.fieldAlias == fieldAlias.split('.')[1],
      );
    },
    getRelactionNode(fieldAlias) {
      return this.filterFields.filter(
        item => item.fieldAlias == fieldAlias.split('.')[1],
      );
    },
    //Groups转为Scheme
    gainFilterScheme(filters, groups, relation) {
      // console.log('======gainFilterScheme======', groups);

      groups.forEach(group => {
        if (group.IsOff) {
          return true;
        }

        var _childs = group.Children.filter(item => {
          return item.IsOff == false;
        });
        if (_childs.length == 0) {
          //组内项都被置为禁用
          if (group.Children.length > 0) {
            return true;
          }
          //经典模式下，没有值、不是为空或不为空，不添加到查询方案
          if (
            !!this.FilterIsClassic &&
            _.trim(group.ValueName) == '' &&
            _.trim(group.Value) == '' &&
            !['isblank', 'isnotblank'].includes(group.Condition)
          ) {
            return true;
          }
          if (filters.length > 0) {
            filters.push({
              ElementType: 'Relation',
              Relation: group.Relation,
            });
          }
          if (['isblank', 'isnotblank'].includes(group.Condition)) {
            let _filter = {
              ElementType: 'Filter',
              Code: group.Code,
              Condition:
                group.ValueType == 0
                  ? ['isblank', 'isnotblank'].includes(group.Condition)
                    ? group.Condition == 'isblank'
                      ? '='
                      : '<>'
                    : group.Condition
                  : group.Condition.replace('[', '').replace(']', ''),
              Value: ['isblank', 'isnotblank'].includes(group.Condition)
                ? ''
                : group.ValueType == 0
                  ? this.getGroupToSchemeValue(
                    group.DataType,
                    group.Value,
                    group.Condition,
                    group.ValueName,
                  )
                  : group.ValueName,
              Name: this.fixedName(group.Code)
                ? this.fixedName(group.Code)
                : group.Name,
              DataType: group.DataType,
              ValueName:
                group.ValueType == 0
                  ? this.getGroupToSchemeName(
                    group.DataType,
                    group.Value,
                    group.Condition,
                    group.ValueName,
                  )
                  : this.fixedName(group.ValueName)
                    ? this.fixedName(group.ValueName)
                    : group.Value,
              ValueType: group.ValueType,
            };
            filters.push(_filter);
            return;
          }
          //解析relactionNode
          let relationNode = null;
          let multipleList = null;

          if (group.relationNode) {
            try {
              relationNode = JSON.parse(group.relationNode);
            } catch (error) { }
          }
          if (group.multipleList) {
            try {
              multipleList = JSON.parse(group.multipleList);
            } catch (error) { }
          }
          if (multipleList) {
            let field = this.getRelactionNodeConfig(group.Code);
            let filter_dataValue = JSON.parse(field[0].filter_dataValue);
            let value = '';
            multipleList.forEach(element => {
              value += element[filter_dataValue.valueField] + ',';
            });
            if (value) {
              value = value.substring(0, value.length - 1);
            }
            let _filter = {
              ElementType: 'Filter',
              Code: group.Code,
              Condition:
                group.ValueType == 0
                  ? ['isblank', 'isnotblank'].includes(group.Condition)
                    ? group.Condition == 'isblank'
                      ? '='
                      : '<>'
                    : group.Condition
                  : group.Condition.replace('[', '').replace(']', ''),
              Value: value,
              Name: this.fixedName(group.Code)
                ? this.fixedName(group.Code)
                : group.Name,
              DataType: group.DataType,
              ValueName:
                group.ValueType == 0
                  ? this.getGroupToSchemeName(
                    group.DataType,
                    group.Value,
                    group.Condition,
                    group.ValueName,
                  )
                  : this.fixedName(group.ValueName)
                    ? this.fixedName(group.ValueName)
                    : group.Value,
              ValueType: group.ValueType,
            };
            filters.push(_filter);
            return;
          }
          if (relationNode) {
            let field = this.getRelactionNodeConfig(group.Code);
            let filter_dataValue = JSON.parse(field[0].filter_dataValue);
            let dataSource = filter_dataValue.customResults_result.dataSource;
            dataSource.forEach(jj => {
              jj._field = this.getRelactionNode('.' + jj.Value)[0];
            });
            //搜索类型的时候，查询房钱的条件
            if (relationNode.length == 0) {
              let _filters = [];
              let filter = '';
              //固定分级码
              if (filter_dataValue.type == 1) {
                let layer = null;
                let classiFicationCode =
                  group.ValueType == 0
                    ? this.getGroupToSchemeValue(
                      group.DataType,
                      group.Value,
                      group.Condition,
                      group.ValueName,
                    )
                    : group.ValueName;
                if (!classiFicationCode) {
                  classiFicationCode = '';
                }
                //固定分级码
                if (filter_dataValue.isClassiFicationSteps) {
                  let step = filter_dataValue.classiFicationStep;
                  layer = classiFicationCode.toString().length / step;
                } else {
                  let steps =
                    filter_dataValue.classiFicationStepRule.split('-');
                  let length = classiFicationCode.toString().length;
                  steps.forEach((jj, index) => {
                    length = length - jj;
                    if (length == 0) {
                      layer = index + 1;
                    }
                  });
                }
                let target = dataSource.filter(ll => {
                  if (ll.filterLabelOptions.indexOf('last') != -1) {
                    if (
                      dataSource.some(
                        kk =>
                          kk.filterLabelOptions.indexOf('layer' + layer) != -1,
                      )
                    )
                      return false;
                    return true;
                  }
                  return ll.filterLabelOptions.indexOf('layer' + layer) != -1;
                });
                if (target.length > 1) {
                  target = target.filter(
                    item => item.filterLabelOptions.indexOf('value') != -1,
                  )[0];
                }
                if (target) {
                  let _filter = {
                    ElementType: 'Filter',
                    Code:
                      target._field.tableAlias + '.' + target._field.fieldAlias,
                    Condition:
                      group.ValueType == 0
                        ? ['isblank', 'isnotblank'].includes(group.Condition)
                          ? group.Condition == 'isblank'
                            ? '='
                            : '<>'
                          : group.Condition
                        : group.Condition.replace('[', '').replace(']', ''),
                    Value: ['isblank', 'isnotblank'].includes(group.Condition)
                      ? ''
                      : group.ValueType == 0
                        ? this.getGroupToSchemeValue(
                          group.DataType,
                          group.Value,
                          group.Condition,
                          group.ValueName,
                        )
                        : group.ValueName,
                    Name: this.fixedName(group.Code)
                      ? this.fixedName(group.Code)
                      : group.Name,
                    DataType: group.DataType,
                    ValueName:
                      group.ValueType == 0
                        ? this.getGroupToSchemeName(
                          group.DataType,
                          group.Value,
                          group.Condition,
                          group.ValueName,
                        )
                        : this.fixedName(group.ValueName)
                          ? this.fixedName(group.ValueName)
                          : group.Value,
                    ValueType: group.ValueType,
                  };
                  filters.push(_filter);
                }
                return;
              }
              dataSource.forEach(jj => {
                let _filter = {
                  ElementType: 'Filter',
                  Code: jj._field.tableAlias + '.' + jj._field.fieldAlias,
                  Condition:
                    group.ValueType == 0
                      ? ['isblank', 'isnotblank'].includes(group.Condition)
                        ? group.Condition == 'isblank'
                          ? '='
                          : '<>'
                        : group.Condition
                      : group.Condition.replace('[', '').replace(']', ''),
                  Value: ['isblank', 'isnotblank'].includes(group.Condition)
                    ? ''
                    : group.ValueType == 0
                      ? this.getGroupToSchemeValue(
                        group.DataType,
                        group.Value,
                        group.Condition,
                        group.ValueName,
                      )
                      : group.ValueName,
                  Name: this.fixedName(group.Code)
                    ? this.fixedName(group.Code)
                    : group.Name,
                  DataType: group.DataType,
                  ValueName:
                    group.ValueType == 0
                      ? this.getGroupToSchemeName(
                        group.DataType,
                        group.Value,
                        group.Condition,
                        group.ValueName,
                      )
                      : this.fixedName(group.ValueName)
                        ? this.fixedName(group.ValueName)
                        : group.Value,
                  ValueType: group.ValueType,
                };
                _filters.push(_filter);
                _filters.push({
                  ElementType: 'Relation',
                  Relation: 'or',
                });
              });
              if (
                _filters[_filters.length - 1] &&
                _filters[_filters.length - 1].ElementType == 'Relation'
              ) {
                _filters.pop();
              }
              filters.push({
                ElementType: 'Group',
                Filters: _filters,
              });
              return;
            }
            let layer = null;
            let _filter = null;
            let last = null;
            relationNode.forEach((kk, index) => {
              let target = dataSource.filter(ll => {
                if (ll.filterLabelOptions.indexOf('last') != -1) {
                  if (
                    dataSource.some(
                      kk =>
                        kk.filterLabelOptions.indexOf(
                          'layer' + relationNode.length,
                        ) != -1,
                    )
                  )
                    return false;
                  last = relationNode.length;
                  return 'layer' + relationNode.length == 'layer' + kk.level;
                }
                return ll.filterLabelOptions.indexOf('layer' + kk.level) != -1;
              });
              let _field = null;

              if (target[0]) {
                target.forEach(ll => {
                  _field = ll._field;
                  if (_field) {
                    let filterLabelOptions = ll.filterLabelOptions;
                    if (filterLabelOptions.indexOf('_last') != -1) {
                      filterLabelOptions.replace(/_last/gi, last);
                    }
                    if (!layer) {
                      layer = ll.filterLabelOptions;
                    } else {
                      if (layer < ll.filterLabelOptions) {
                        layer = ll.filterLabelOptions;
                      } else {
                        return;
                      }
                    }
                    _filter = {
                      ElementType: 'Filter',
                      Code: _field.tableAlias + '.' + _field.fieldAlias,
                      Condition:
                        group.ValueType == 0
                          ? ['isblank', 'isnotblank'].includes(group.Condition)
                            ? group.Condition == 'isblank'
                              ? '='
                              : '<>'
                            : group.Condition
                          : group.Condition.replace('[', '').replace(']', ''),
                      Value: ['isblank', 'isnotblank'].includes(group.Condition)
                        ? ''
                        : ll.filterLabelOptions.indexOf('.value') != -1
                          ? kk[filter_dataValue.valueField]
                          : kk[filter_dataValue.labelField],
                      Name: '',
                      DataType: group.DataType,
                      ValueName: '',
                      ValueType: group.ValueType,
                    };
                  }
                });
              }
            });
            filters.push(_filter);
            return;
          }
          let _filter = {
            ElementType: 'Filter',
            Code: group.Code,
            Condition:
              group.ValueType == 0
                ? ['isblank', 'isnotblank'].includes(group.Condition)
                  ? group.Condition == 'isblank'
                    ? '='
                    : '<>'
                  : group.Condition
                : group.Condition.replace('[', '').replace(']', ''),
            Value: ['isblank', 'isnotblank'].includes(group.Condition)
              ? ''
              : group.ValueType == 0
                ? this.getGroupToSchemeValue(
                  group.DataType,
                  group.Value,
                  group.Condition,
                  group.ValueName,
                )
                : group.ValueName,
            Name: this.fixedName(group.Code)
              ? this.fixedName(group.Code)
              : group.Name,
            DataType: group.DataType,
            ValueName:
              group.ValueType == 0
                ? this.getGroupToSchemeName(
                  group.DataType,
                  group.Value,
                  group.Condition,
                  group.ValueName,
                )
                : this.fixedName(group.ValueName)
                  ? this.fixedName(group.ValueName)
                  : group.Value,
            ValueType: group.ValueType,
          };
          filters.push(_filter);
        } else {
          if (filters.length > 0) {
            filters.push({
              ElementType: 'Relation',
              Relation: group.Relation,
            });
          }
          var _group = {
            ElementType: 'Group',
            Filters: [],
          };
          filters.push(_group);
          this.gainFilterScheme(_group.Filters, _childs);
        }
      });
    },
    fixedName(code) {
      if (typeof code !== 'string') return '';

      let res = this.FieldsConfig.find(item => {
        return (
          item.tableAlias == code.split('.')[0] &&
          item.tableAlias == code.split('.')[0] &&
          item.fieldAlias == code.split('.')[1]
        );
      });

      return res ? res.fieldName : '';
    },
    //方案结构真实值转换
    convertExp(farr) {
      farr.forEach((f, i) => {
        if (!f) {
          return;
        }

        try {
          f = JSON.parse(f);
        } catch (error) { }

        let cv = f.value || f.Value || f;
        if (typeof cv == 'string' && cv.includes('@')) {
          let ccv = Funcs.AtVarTransform(cv);

          // if (typeof ccv == 'object') {
          //   ccv = Object.keys(ccv)
          //     .map(k => {
          //       return ccv[k];
          //     })
          //     .filter(ccvf => ccvf)
          //     .join();

          //   farr[1] =
          //     farr[1] == '=' ? 'in' : farr[1] == '<>' ? 'notin' : farr[1];
          // }

          farr[i] = ccv;
        } else if (f && f.push) {
          convertExp(f);
        }
      });
    },
    //获取有条件值的条件组
    getValuesGroups() {
      let _groups = [];

      this.FilterGroups.forEach(group => {
        if (
          (_.trim(group.Value) != '' &&
            _.trim(group.ValueName) != '' &&
            group.Value != `<${this.Term.field.inputValue}>`) ||
          ['isblank', 'isnotblank'].includes(group.Condition)
        ) {
          _groups.push(_.cloneDeep(group));
        }
      });

      return _groups;
    },
    //查询条件对应的查询方案
    getFilterScheme() {
      var _scheme = {
        ElementType: 'Group',
        Filters: [],
      };
      this.gainFilterScheme(_scheme.Filters, this.FilterGroups);
      //只有一个查询项，并且该查询项为查询组，拿出去
      if (
        _scheme.Filters.length == 1 &&
        _scheme.Filters[0].ElementType == 'Group'
      ) {
        _scheme.Filters = _scheme.Filters[0].Filters;
      }
      return _scheme;
    },
    getFilterExpression() {
      var _scheme = _.cloneDeep(this.FilterScheme);
      // this.convertExp(_scheme.Filters);
      return _scheme;
    },
    getSchemeToGroupValue(
      dataType,
      dataValue,
      condition,
      dataValueName,
      dataValueType,
    ) {
      var _realValue = dataValue;
      if (condition != 'between' || !Array.isArray(_realValue)) {
        if (dataValueType == 0) {
          return dataValueName;
        } else {
          return dataValue;
        }
      }

      return _realValue.join(' - ');
    },
    //兼容历史数据
    getBetweenGroupValue(valueName) {
      let _value = valueName;

      switch (_.trim(_value)) {
        case '@今日初 - @今日末':
          _value = '@今天';
          break;
        case '@昨日初 - @昨日末':
          _value = '@昨天';
          break;
        case '@本周一 - @本周日':
          _value = '@本周';
          break;
        case '@上周一 - @上周日':
          _value = '@上周';
          break;
        case '@本月初 - @本月末':
          _value = '@本月';
          break;
        case '@上月初 - @上月末':
          _value = '@上月';
          break;
        case '@今年初 - @今年末':
          _value = '@今年';
          break;
        case '@上年初 - @上年末':
          _value = '@上年';
          break;
        default:
          break;
      }

      return _value;
    },
    getGroupToSchemeValue(dataType, dataValue, condition, dataValueName) {
      if (dataValue === '' || dataValueName === '') {
        return '';
      }
      //非区间类型
      if (condition != 'between') {
        //非时间类型
        if (!['date', 'datetime', 'timestamp'].includes(_.toLower(dataType))) {
          return dataValueName;
        } else {
          if (dataValue == null || dataValue.indexOf('@') == -1) {
            return dataValueName;
          } else {
            let _term =
              _timeVar.filter(tv =>
                dataValue.startsWith('@' + Funcs.GetTerms(tv.code, tv.zh)),
              ) || [];
            _term = _term[0] || {};
            if (!!_term.code) {
              return dataValue.replace(
                '@' + Funcs.GetTerms(_term.code, _term.zh),
                _term.zh,
              );
            } else {
              return dataValueName;
            }
          }
        }
      }

      //非时间类型
      if (!['date', 'datetime', 'timestamp'].includes(_.toLower(dataType))) {
        return Array.isArray(dataValue) ? dataValue : dataValue.split(' - ');
      }

      //兼容历史数据
      if (!Array.isArray(dataValue) && dataValue.indexOf(' - ') != -1) {
        return dataValue.split(' - ');
      }

      //国际化词语转为中文
      let _term =
        _timeVar.filter(
          tv => '@' + Funcs.GetTerms(tv.code, tv.zh) == dataValue,
        ) || [];
      _term = _term[0] || {};
      if (!!_term.code) {
        dataValue = _term.zh;
      }

      let _values = '@今日初 - @今日末'.split(' - ');
      switch (_.trim(dataValue)) {
        case '@近3天':
          _values = '@今天-2 - @今日末'.split(' - ');
          break;
        case '@近7天':
          _values = '@今天-6 - @今日末'.split(' - ');
          break;
        case '@今天':
          _values = '@今日初 - @今日末'.split(' - ');
          break;
        case '@昨天':
          _values = '@昨日初 - @昨日末'.split(' - ');
          break;
        case '@本周':
          _values = '@本周一 - @本周日'.split(' - ');
          break;
        case '@上周':
          _values = '@上周一 - @上周日'.split(' - ');
          break;
        case '@本月':
          _values = '@本月初 - @本月末'.split(' - ');
          break;
        case '@上月':
          _values = '@上月初 - @上月末'.split(' - ');
          break;
        case '@今年':
          _values = '@今年初 - @今年末'.split(' - ');
          break;
        case '@上年':
          _values = '@上年初 - @上年末'.split(' - ');
          break;
        default:
          break;
      }

      return _values;
    },
    getGroupToSchemeName(dataType, dataValue, condition, dataValueName) {
      //非区间类型，非时间类型，不做处理
      if (
        condition != 'between' ||
        !['date', 'datetime', 'timestamp'].includes(_.toLower(dataType))
      ) {
        return dataValue;
      }

      if (dataValue.indexOf(' - ') == -1 || dataValue.indexOf('@') == -1) {
        return dataValue;
      }

      //兼容历史数据
      let _value = '@今天';
      switch (_.trim(dataValue)) {
        case '@今日初 - @今日末':
          _value = '@今天';
          break;
        case '@昨日初 - @昨日末':
          _value = '@昨天';
          break;
        case '@本周一 - @本周日':
          _value = '@本周';
          break;
        case '@上周一 - @上周日':
          _value = '@上周';
          break;
        case '@本月初 - @本月末':
          _value = '@本月';
          break;
        case '@上月初 - @上月末':
          _value = '@上月';
          break;
        case '@今年初 - @今年末':
          _value = '@今年';
          break;
        case '@上年初 - @上年末':
          _value = '@上年';
          break;
        default:
          break;
      }

      return _value;
    },
    changeApply() {
      // alert('=========== changeApply');

      try {
        this.$emit('apply', arguments, true);
      } catch (e) { }

      if (!!this.isStopApply && this.isStopApply != 'false') {
        return false;
      }

      if (!!this.associationScheme) {
        // this.AdvQueryInstances.updateAdvQuery(this.FilterScheme);
        if (this.FilterIsChange) {
          this?.associationScheme?.updateAdvQuery('filter');
        }
        this?.associationScheme?.Query();
        // alert('changeApply updateAdvQuery');
      }

      this.InitGroups = _.cloneDeep(this.FilterGroups);
      this.FilterIsChange = false;
    },
    filterQuery: async function () {
      // alert('=========== filterQuery');
      const ret = {
        valid: false,
      };

      //修改为主动查询
      this.quckFilterInstance?.statisticalQuery();
      try {
        this.$emit('query', arguments, true);
        // this?.associationScheme?.query('filter');
      } catch (e) {
        // console.log('filterQuery error', e);
      }

      // 通过返回 Promise 实现异步化
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          // 通过宏任务的方式，延后对页面脚本逻辑执行结果的判断
          if (!!this.isStopApply && this.isStopApply != 'false') {
            resolve(ret);
            return;
          }

          if (!!this.associationScheme) {
            if (this.FilterIsChange) {
              // this.AdvQueryInstances.updateAdvQuery(this.FilterScheme);
              this?.associationScheme?.updateAdvQuery('filter');
            }
            this?.associationScheme?.Query();
            ret.valid = true;
          }
          this.FilterIsChange = false;
          resolve(ret);
        });
      });
    },
    queryApply() {
      try {
        this.$emit('query', arguments, true);
        // this?.associationScheme?.query('filter');
      } catch (e) { }

      if (!!this.isStopApply && this.isStopApply != 'false') {
        return false;
      }

      if (!!this.associationScheme) {
        // this.associationScheme.updateAdvQuery(this.FilterScheme);
        if (this.FilterIsChange) {
          this.associationScheme.updateAdvQuery('filter');
        }
        this?.associationScheme?.Query();
        // alert('queryApply updateAdvQuery');
      }

      this.InitGroups = _.cloneDeep(this.FilterGroups);
      this.FiltersIsShow = false;
    },
    clearQuery() {
      this.FilterGroups.forEach(filter => {
        if (['isblank', 'isnotblank'].includes(filter.Condition)) {
          filter.Condition = '=';
        }

        filter.Value = '';
        filter.ValueName = '';
      });
    },
    resetQuery() {
      this.FilterGroups = [];
      if (this.InitGroups.length == 0) {
        this.FilterGroups = this.GetFieldGroups(this.InitGroups);
      } else {
        let _groups = _.cloneDeep(this.InitGroups);
        _groups.forEach(filter => {
          let _field = this.FieldsConfig.filter(
            item =>
              item.tableAlias +
              '.' +
              (item.tableAlias != '__UserDefineColumns'
                ? item.fieldCode
                : item.fieldAlias) ==
              filter.Code,
          );

          _field = _field[0] || {};
          if (!_field.ID) {
            return false;
          }

          let _config = {
            ColNum: 6,
            IsCommUse: true,
            InitValue: '',
            DependCodes: [],
            IsCompDepend: false,
          };
          try {
            if (_field.filter_classicConfig) {
              _config =
                typeof _field.filter_classicConfig == 'string'
                  ? JSON.parse(_field.filter_classicConfig)
                  : _field.filter_classicConfig;

            }
          } catch (e) { }

          filter.ColNum = _config.ColNum || 6;
        });

        this.FilterGroups = _groups;
      }

      this.$nextTick(() => {
        try {
          this.$emit('reset', arguments, true);
        } catch (e) { }
      });
    },
    FilterCheckMust() {
      return this.$refs['filters_panel'].checkMust();
    },
    FilterCheckInput() {
      return this.$refs['filters_panel'].checkInput()
    },
    FilterChange() {
      this.$emit('change', arguments);

      //复杂模式不处理依赖关系
      if (!this.FilterIsEasy) {
        return true;
      }

      //条件依赖处理
      this.FilterGroups.forEach(_filter => {
        let _field = this.FieldsConfig.filter(
          item =>
            item.tableAlias +
            '.' +
            (item.tableAlias != '__UserDefineColumns'
              ? item.fieldCode
              : item.fieldAlias) ==
            _filter.Code,
        );
        _field = _field[0] || {};

        if (!_field.ID) {
          return false;
        }

        let _config = {
          ColNum: 6,
          IsCommUse: true,
          InitValue: '',
          DependCodes: [],
          IsCompDepend: false,
        };
        try {


          if (_field.filter_classicConfig) {
            _config =
              typeof _field.filter_classicConfig == 'string'
                ? JSON.parse(_field.filter_classicConfig)
                : _field.filter_classicConfig;
          }
        } catch (e) {

        }

        if (
          !_config.DependCodes ||
          _config.DependCodes.length == 0 ||
          !_config.IsCompDepend
        ) {
          return false;
        }

        try {
          _config.DependCodes.forEach(_pend => {
            let _pender = this.FilterGroups.filter(item => item.Code == _pend);
            _pender = _pender[0] || {};

            //强依赖的条件为空，清空条件
            if (
              !_pender.ID ||
              _pender.Value == '' ||
              _pender.ValueName == '' ||
              _pender.Value == `<${this.Term.field.inputValue}>` ||
              _pender.ValueName == `<${this.Term.field.inputValue}>`
            ) {
              if (this.FilterIsClassic) {
                _filter.Value = '';
                _filter.ValueName = '';
              } else {
                _filter.Value = `<${this.Term.field.inputValue}>`;
                _filter.ValueName = `<${this.Term.field.inputValue}>`;
              }

              throw new Error('');
            }
          });
        } catch (e) { }
      });
    },
    GetCurrDownHelper() {
      return window.Fas_FilterCurrHelper || null;
    },
    GetInitValueByScript(strScript, field, filter) {
      if (!window.TeldWebConfig) return {
        Name:'',
        Value:''
      }
      let _initValue = {};
      let _tempValue = '';
      try {
        _tempValue =
          typeof strScript == 'function'
            ? strScript()
            : Object.prototype.toString.call(strScript) === '[object Object]'
              ? strScript
              : new Function(strScript)();
        if (typeof _tempValue === 'undefined') _tempValue = strScript;
        // _tempValue = this.execClientScript(
        //   this.warpJSScriptBindContext(
        //     `
        //     /**
        //      * Data: {"field":"字段配置","filter":"条件信息"}
        //     */
        //     debugger;
        //     ${strScript || ''}
        //     `,
        //     { Data: { field: field, filter: filter }, Handler: null },
        //   ),
        // );
      } catch (e) { }

      if (typeof _tempValue == 'string' && _.trim(_tempValue) != '') {
        _initValue['Value'] = _tempValue;
        _initValue['Name'] = _tempValue;
      } else if (
        Object.prototype.toString.call(_tempValue) === '[object Object]'
      ) {
        if (!!_tempValue.Value) {
          _initValue['Value'] = _tempValue.Value;
        }
        if (!!_tempValue.Name) {
          _initValue['Name'] = _tempValue.Name;
        }
      }

      return _initValue;
    },
    GetValueByScript(strScript, field, filter) {
      if (!window.TeldWebConfig) return {
        Name:'',
        Value:''
      }
      let _initValue = {};
      let _tempValue = '';
      try {
        _tempValue =
          typeof strScript == 'function'
            ? strScript()
            : Object.prototype.toString.call(strScript) === '[object Object]'
              ? strScript
              : new Function(strScript)();
        if (typeof _tempValue === 'undefined') _tempValue = strScript;
      } catch (e) { }

     

      return _tempValue;
    },
    //以条件配置为主覆盖条件组
    GetFieldGroups(groups, exctLoadInitValue) {
      let _groups = [];

      this.FieldsConfig.filter(item => item.isQuery).forEach(_field => {
        let _filter = groups.filter(
          g =>
            g.Code ==
            _field.tableAlias +
            '.' +
            (_field.tableAlias != '__UserDefineColumns'
              ? _field.fieldCode
              : _field.fieldAlias),
        );
        _filter = _filter[0] || {};

        if (!!_filter.IsOff) return;

        let _config = {
          ColNum: 6,
          IsCommUse: true,
          InitValue: '',
          DependCodes: [],
          IsCompDepend: false,
        };
        try {

          if (_field.filter_classicConfig) {
            _config =
              typeof _field.filter_classicConfig == 'string'
                ? JSON.parse(_field.filter_classicConfig)
                : _field.filter_classicConfig;
            if (_config && _config.helpTipContext && _config.helpTipContextReferenceExpr) {
              _config.helpTipContext = window.Funcs?.GetTerms(_config.helpTipContextReferenceExpr, _config.helpTipContext) || _config.helpTipContext

            }
          }
        } catch (e) {

        }

        if (!_config.IsCommUse) return;

        let _initValue = {};
        if (!!_config.InitValue && !exctLoadInitValue) {
          _initValue = this.GetInitValueByScript(
            _config.InitValue,
            _field,
            _filter,
          );
        }
        let placeholderContext={}
        if(_config&&_config.enablePlaceholder&&_config.placeholderContext){
       
          try {
            placeholderContext =  this.GetValueByScript(
              _config.placeholderContext,
            _field,
            null,
          );
            eval('console.log(placeholderContext)')
          } catch (error) {
            eval('console.log(error)')
          }

        }
        //兼容历史数据，条件关系历史数据可能为汉字
        if (!!_field.field_condition) {
          let _list = [
            { Name: '等于', Code: '=' },
            { Name: '大于', Code: '>' },
            { Name: '大于等于', Code: '>=' },
            { Name: '小于', Code: '<' },
            { Name: '小于等于', Code: '<=' },
            { Name: '不等于', Code: '<>' },
            { Name: '包含', Code: 'contains' },
            { Name: '不包含', Code: 'notcontains' },
            { Name: '开始于', Code: 'startswith' },
            { Name: '结束于', Code: 'endswith' },
            { Name: '隶属', Code: 'i' },
            { Name: '非隶属', Code: 'notin' },
          ];
          let _his = _list.filter(item => item.Name == _field.field_condition);

          _his = _his[0] || {};
          _field.field_condition = !!_his.Code
            ? _his.Code
            : _field.field_condition;
        }

        let _condition =
          _filter.Condition ||
          (!!_field.field_condition
            ? [
              '=',
              '>',
              '>=',
              '<',
              '<=',
              '<>',
              'between',
              'contains',
              'notcontains',
              'in',
              'notin',
            ].includes(_field.field_condition)
              ? _field.field_condition
              : '='
            : ['date', 'time'].includes(_field.filter_inputWay) ||
              ['Int', 'DateTime', 'Date'].includes(_field.dataType)
              ? 'between'
              : '=');
        _groups.push({
          ID: _field.ID,
          Type: 'Filter',
          Relation: 'and',
          Code:
            _filter.Code ||
            _field.tableAlias +
            '.' +
            (_field.tableAlias != '__UserDefineColumns'
              ? _field.fieldCode
              : _field.fieldAlias),
          Name: _filter.Name || _field.fieldName,
          Condition: _condition,
          Value:
            (_condition == 'between' && _filter.Value == ' - ') ||
              _filter.Value == `<${this.Term.field.inputValue}>` ||
              !_filter.ID
              ? _initValue.Name === '' ||
                _initValue.Name === null ||
                _initValue.Name === undefined
                ? ''
                : _initValue.Name
              : _filter.Value,
          DataType: _field.dataType,
          ValueName:
            (_condition == 'between' && _filter.ValueName == ' - ') ||
              _filter.Value == `<${this.Term.field.inputValue}>` ||
              !_filter.ID
              ? _initValue.Value === '' ||
                _initValue.Value === null ||
                _initValue.Value === undefined
                ? ''
                : _initValue.Value
              : _filter.ValueName,
          ValueType: _filter.ValueType || 0,
          IsOff: false,
          Children: [],
          ColNum: _config.ColNum || 6,
          enableHelpTip: _config.enableHelpTip,
          helpTipPlacement: _config.helpTipPlacement,
          helpTipContext: _config.helpTipContext,
          helpTipContextReferenceExpr: _config.helpTipContextReferenceExpr,
          filter_isMust:_field.filter_isMust,
          ...placeholderContext
        });
      });

      return _groups;
    },
    // 设置快速筛选默认选中内容
    setQuickFilterFilters(SelectedItem, notQuery) {
      // {State: 1, IsDelete: '', LastModifyTime: null}
      // Widget.fasr_filter.quckFilterInstance.setSelectedItem({'DutyDepartmentID':'2f4da147-2a59-4928-b426-1d14e776d57d','IsDelete':"true"})
      this.quckFilterInstance?.setSelectedItem(SelectedItem)
      this.$refs.filters_panel?.getQuickFilter()
      if (!notQuery) {
        this.filterQuery()
      }

    },
    clearQuckFilterFilters() {
      this.$refs.filters_panel.$refs.fasr_quick_filter?.clearSelected()
      this.$refs.filters_panel?.getQuickFilter()
    },
    // 查询方案会调用
    setFilters(filter, FilterModel,notClearQuckFilter) {

      

      // 是否处理依赖关系
      window['Fas_FilterIsDealDepend'] = false;

      this.FilterGroups = [];
      this.FilterIsInit = true;

      // this.FilterIsChange = true; //初始化值变化

      //每次设置都需要重新判断一下设计时是否是默认经典
      this.FilterIsClassic = !!this.isClassic;

      //条件组
      let _groups = [];
      //是否用户“已存”的经典模式
      let _isClisic = false;

      if (Array.isArray(filter)) {
        _groups = filter;
      } else if (!!filter.FilterModel && !!filter.FilterGroups) {
        // 新方案内容
        _groups = filter.FilterGroups;
        const { FilterModel } = filter;
        _isClisic = FilterModel == 'Classic';
        this.FilterIsClassic = _isClisic;
        this.FilterIsEasy = FilterModel != 'Comp';
      } else {
        //兼容历史数据
        // 因为移动端导致的兼容处理 20240510 刁春辉老师提出的改动
        if (FilterModel) {
          _isClisic = FilterModel == 'Classic';
          this.FilterIsClassic = _isClisic;
          // 其实不可能是复杂模式，但是以防万一
          this.FilterIsEasy = FilterModel != 'Comp';
        }

        this.getFitlterGroups(_groups, filter.Filters, null, false);
      }

      //经典模式一定是简单模式
      if (!!this.FilterIsClassic) {
        this.FilterIsEasy = true;

        //不是用户 已存 的经典模式条件，根据列配置覆盖条件组，强制用户自己操作下，保证下次是用户自己保存的条件组
        _groups = this.GetFieldGroups(_groups);
        // if (true || !_isClisic) {
        // } else
        {
          //检查用户保存的条件，现在还是否支持，不支持的删除掉
          //循环次数
          let _loop = _groups.length;
          //遍历数组
          for (let i = 0; i < _loop; i++) {
            //如果字段配置中不存在该条件编码
            if (
              this.FieldsConfig.filter(
                item =>
                  item.tableAlias +
                  '.' +
                  (item.tableAlias != '__UserDefineColumns'
                    ? item.fieldCode
                    : item.fieldAlias) ==
                  _groups[i].Code,
              ).length == 0
            ) {
              //从i位置开始删除1个
              _groups.splice(i, 1);
              //改变循环变量
              i = i - 1;
              //改变循环次数
              _loop = _loop - 1;
            }
          }
        }
      } else {
        //  this.FilterIsEasy = !_groups.filter(g => { return g.Children.length > 0 }).length;
      }

      this.todayTerms = getTextByCode(
        this.termList,
        'Schema.Controls.fas_filter.Terms.date.today',
      );
      this.dealTermFilter(_groups);
      if (this.enableQuickFilter === '1'&&!notClearQuckFilter) {
        setTimeout(() => {
          this.clearQuckFilterFilters()
        }, 200);

      }
      //读取用户配置信息
      // if (!!this.FilterIsClassic) {
      try {
        if (!this.IniLoadedFiltersIsShow) {

          if (this.isCollapse === '0') {
            if ((this.enableQuickFilter === '0' && this.isShowTopContent === '0')) {
              this.FiltersIsShow = true
            } else {
              this.FiltersIsShow = false
            }
            this.IniLoadedFiltersIsShow = true;
            return this.FilterGroups = _groups;

          }

          this.GetUserProfile(this.getUserPlanKey()).then(data => {
            if(  data[0].ConfigValue === ''){
              return this.FiltersIsShow = true;
            }
            this.FiltersIsShow =
              Array.isArray(data) &&
              data.length > 0 &&
              data[0].ConfigID == 'IsUnfold' &&
              data[0].ConfigValue == '1';
            this.IniLoadedFiltersIsShow = true;
          });



        } else {
          // this.FiltersIsShow = true;
        }
      } catch (e) { }
      // } else {
      //   this.FiltersIsShow = true;
      // }

      this.InitGroups = _.cloneDeep(_groups);
      this.FilterGroups = _groups;
    },

    //处理国际化条件项
    dealTermFilter(groups) {
      groups.forEach(_filter => {
        // console.log('=======_filter=======', _filter);
        if (_filter.Children.length > 0) {
          this.dealTermFilter(_filter.Children);
          return true;
        }

        let _field = this.FieldsConfig.filter(
          item =>
            item.tableAlias +
            '.' +
            (item.tableAlias != '__UserDefineColumns'
              ? item.fieldCode
              : item.fieldAlias) ==
            _filter.Code,
        );
        _field = _field[0] || {};

        if (!_field.ID) {
          return true;
        }

        //条件名称转换
        _filter.Name =
          Funcs.GetTerms(
            _field?.ValueInfo_fieldName?.ReferenceExpr,
            _field.fieldName,
          ) || _filter.Name;

        //时间转换
        try {
          // if (_filter.ValueName.indexOf("@今天") != -1)
          // {
          //   _filter.ValueName = _filter.ValueName.replace("@今天", `@${Terms.date.today}`);
          //   _filter.Value = _filter.ValueName;
          // }

          let terms_sg = null;
          let terms_code = null;
          let value_zh_cn = null;
          this.termList.forEach(item => {
            let targetTranslateItems = null;
            if (item.Code == 'Schema.Controls.fas_filter.Terms.date.today') {
              targetTranslateItems = item.TranslateItems.find(TranslateItems =>
                _filter.ValueName.startsWith(
                  `@${TranslateItems.TranslateText}`,
                ),
              );
            } else {
              targetTranslateItems = item.TranslateItems.find(
                TranslateItems =>
                  _filter.ValueName == `@${TranslateItems.TranslateText}`,
              );
            }

            if (targetTranslateItems) {
              value_zh_cn = item.TranslateItems.find(
                TranslateItems => TranslateItems.Language == 'zh-CN',
              ).TranslateText;
              terms_code = item.Code;
              terms_sg = targetTranslateItems.TranslateText;
            }
          });

          // console.log(
          //   '=====_filter.ValueName=====',
          //   _filter.ValueName,
          //   terms_sg,
          //   terms_code,
          // );
          // if (this.todayTerms.some(n => _filter.ValueName.startsWith(`@${n}`)))
          // {
          //   const todayTerm = this.todayTerms.find(n => _filter.Value.includes(n));
          //   _filter.Value = _filter.Value.replace(todayTerm, Terms.date.today); // value存中文，方案组件需要
          // }
          if (terms_code) {
            _filter.Value = _filter.ValueName.replace(
              terms_sg,
              Funcs.GetTerms(terms_code, _filter.Value),
            );
            _filter.ValueName = _filter.ValueName.replace(
              terms_sg,
              Funcs.GetTerms(terms_code, value_zh_cn),
            ); // value存中文，方案组件需要
            // console.log(_filter);
          } else {
            let _term = _timeTerms.filter(temp => temp.zh == _filter.ValueName);
            _term = _term[0] || {};

            if (!!_term.zh) {
              _filter.ValueName = _term.term;
              _filter.Value = _filter.ValueName;
            }
          }
        } catch (e) {
          // console.log(e);
        }

        //下拉固定字典转换
        if (!!_field.ID && _field.filter_dataType == 'fixed') {
          //国际化词条
          let _text = _filter.Value;

          if (
            !!_field.filter_dataValueList_Schema &&
            Array.isArray(_field.filter_dataValueList_Schema) &&
            _field.filter_dataValueList_Schema.length > 0
          ) {
            let _term =
              _field.filter_dataValueList_Schema.filter(
                temp => temp.ShowValue == _text,
              )[0] || {};
            _text = Funcs.GetTerms(_term.ReferenceExpr || '', _text);
          }

          _filter.Value = _text;
        }
      });
    },

    getFilters() {
      let _filter = {
        Scheme: this.FilterScheme,
        Groups: {
          FilterModel: !!this.FilterIsClassic
            ? 'Classic'
            : this.FilterIsEasy
              ? 'Easy'
              : 'Comp',
          FilterGroups: this.FilterGroups,
        },
      };

      return _filter;
    },
    setFields(fields) {
      this.FilterGroups = [];
      this.InitGroups = _.cloneDeep(this.FilterGroups);

      this.FieldsConfig = fields;
    },
    getFields() {
      return _.cloneDeep(this.FieldsConfig);
    },
    getValueByCode(code) {
      let _result = { Value: '', Name: '' };
      let _filter = this.FilterGroups.filter(
        item => item.Code.split('.').includes(code) || item.Code == code,
      );

      _filter = _filter[0] || {};
      _result.Value = _filter.ValueName || '';
      _result.Name = _filter.Value || '';

      return _result;
    },
    setValueByCode(code, data) {
      if (
        !(Object.prototype.toString.call(data) === '[object Object]') ||
        !data.Value ||
        !data.Name
      ) {
        return false;
      }

      let _filter = this.FilterGroups.filter(
        item => item.Code.split('.').includes(code) || item.Code == code,
      );

      _filter = _filter[0] || {};

      if (!_filter.ID) {
        return false;
      }

      _filter.Value = data.Value;
      _filter.ValueName = data.Name;

      return true;
    },
    addFilterItem(code, data) {
      if (
        !(Object.prototype.toString.call(data) === '[object Object]') ||
        (data.Value === null || data.Value === '' || data.Value === undefined) ||
        !data.Name
      ) {
        return false;
      }

      let _field = this.FieldsConfig.filter(
        item =>
          item.fieldCode == code ||
          item.tableAlias +
          '.' +
          (item.tableAlias != '__UserDefineColumns'
            ? item.fieldCode
            : item.fieldAlias) ==
          code,
      );

      _field = _field[0] || {};

      if (!_field.ID) {
        return false;
      }

      //兼容历史数据，条件关系历史数据可能为汉字
      if (!!_field.field_condition) {
        let _list = [
          { Name: '等于', Code: '=' },
          { Name: '大于', Code: '>' },
          { Name: '大于等于', Code: '>=' },
          { Name: '小于', Code: '<' },
          { Name: '小于等于', Code: '<=' },
          { Name: '不等于', Code: '<>' },
          { Name: '包含', Code: 'contains' },
          { Name: '不包含', Code: 'notcontains' },
          { Name: '开始于', Code: 'startswith' },
          { Name: '结束于', Code: 'endswith' },
          { Name: '隶属', Code: 'i' },
          { Name: '非隶属', Code: 'notin' },
        ];
        let _his = _list.filter(item => item.Name == _field.field_condition);

        _his = _his[0] || {};userProfileusefufuseuser
        _field.field_condition = !!_his.Code
          ? _his.Code
          : _field.field_condition;
      }

      this.FilterGroups.push({
        ID: this.getGuid(), //guid
        Type: 'Filter', //条件项固定值
        Relation: 'and', //条件项关系
        Code:
          _field.tableAlias +
          '.' +
          (_field.tableAlias != '__UserDefineColumns'
            ? _field.fieldCode
            : _field.fieldAlias), //根据Widget.fas_filter.FieldsConfig获取列配置信息，取对应字段的  tableAlias.fieldCode
        Name: _field.fieldName, //条件名称
        Condition: !!_field.field_condition
          ? [
            '=',
            '>',
            '>=',
            '<',
            '<=',
            '<>',
            'between',
            'contains',
            'notcontains',
            'in',
            'notin',
          ].includes(_field.field_condition)
            ? _field.field_condition
            : '='
          : '=', //条件关系
        Value: data.Name, //条件显示值
        DataType: _field.dataType,
        ValueName: data.Value, //条件实际取值
        ValueType: 0, //条件项类型，固定项
        IsOff: false, //是否禁用
        Children: [],
      });

      return true;
    },
    getFilterCodes() {
      let _result = [];

      this.FieldsConfig.forEach(item => {
        _result.push(
          item.tableAlias +
          '.' +
          (item.tableAlias != '__UserDefineColumns'
            ? item.fieldCode
            : item.fieldAlias),
        );
      });

      return _result;
    },
    getFilterParas() {
      let _result = {};

      this.FilterGroups.forEach(item => {
        _result[item.Code] = item.ValueName;
      });

      return _result;
    },

    getDynamicFilter() {

      if (this.enableQuickFilter === '1') {

        return this.quckFilterInstance?.getFasDynamicFilter(this.getConvertedFilterExpression())
      }
      let _result = {};

      this.FilterGroups.forEach(item => {
        const { Code = '', ValueName } = item;
        if (Code) {
          const CodeArr = Code.split('.');
          if (
            CodeArr.length > 0 &&
            ValueName !== '' &&
            ValueName !== null &&
            ValueName !== undefined
          ) {
            _result[CodeArr[CodeArr.length - 1]] = ValueName;
          }
        }
      });

      return _result;
    },

    getDependParas(code) {
      let _result = {};

      if (!code || typeof code != 'string' || _.trim(code) == '') {
        return _result;
      }

      let _field = this.FieldsConfig.filter(
        item =>
          item.fieldCode == code ||
          item.tableAlias +
          '.' +
          (item.tableAlias != '__UserDefineColumns'
            ? item.fieldCode
            : item.fieldAlias) ==
          code,
      );
      _field = _field[0] || {};

      if (!_field.ID) {
        return false;
      }

      let _config = {
        ColNum: 6,
        IsCommUse: true,
        InitValue: '',
        DependCodes: [],
        IsCompDepend: false,
      };

      try {
        if (_field.filter_classicConfig) {
          _config =
            typeof _field.filter_classicConfig == 'string'
              ? JSON.parse(_field.filter_classicConfig)
              : _field.filter_classicConfig;
        }
      } catch (e) { }

      if (!_config.DependCodes) {
        return _result;
      }

      this.FilterGroups.filter(item =>
        _config.DependCodes.includes(item.Code),
      ).forEach(item => {
        _result[item.Code] = item.ValueName;
      });

      return _result;
    },
    setFilterShow() {
      this.FiltersIsShow = true;
      return true;
    },
    setFilterHide() {
      this.FiltersIsShow = false;
      return true;
    },
    setApplyShow() {
      this.InitGroups = _.cloneDeep(this.FilterGroups);
      this.FilterIsChange = true;
      return true;
    },
    setApplyHide() {
      this.InitGroups = _.cloneDeep(this.FilterGroups);
      this.FilterIsChange = false;
      return true;
    },
    /* 设置单个配置项 */
    async SaveUserProfile(profileKey, profileValue) {
      if (typeof Funcs == 'undefined') return null;
      // const url = TFF.common.ajax.getServiceUrl('WRP-Runtime-SetUserConfig');
      return Funcs.SetPageUserProfile({   PageID: this.getPageID(),
        profileKey:profileKey,
        profileValue: profileValue}).then(Result => {
        if (Result.state == '1') {
          return Promise.resolve(Result.data);
        } else {
          return Promise.reject(Result.errmsg);
        }
      });
    },
    /* 获取单个配置项 */
    async GetUserProfile(profileKey) {
      if (typeof Funcs == 'undefined') return null;
      // const url = TFF.common.ajax.getServiceUrl('WRP-Runtime-GetUserConfig');
     
      return Funcs.GetPageUserProfile({profileKeys:[profileKey],PageID:this.getPageID()}).then(Result => {
        if (Result.state == '1') {
          return Promise.resolve(Result.data);
        } else {
          return Promise.reject(Result.errmsg);
        }
      });
    },
    TestSaveUserProfile(profileKey, profileValue) {
      this.SaveUserProfile(profileKey, profileValue).then(data => {
        // console.log(JSON.stringify(data));
      });
    },
    TestGetUserProfile(profileKey) {
      this.GetUserProfile(profileKey).then(data => {
        // console.log(JSON.stringify(data));
      });
    },
    getUserPlanKey() {
      return { Key: 'IsUnfold', DynamicKey: '',PageID:this.getPageID()}; //"filter_plan_show_" + this.FilterPlanID;
    },
    //设置用户方案是否折叠
    setUserPlan() {
      if (this.isCollapse === '0') {

        return
      }
      this.SaveUserProfile(
        this.getUserPlanKey(),
        !!this.FiltersIsShow ? '1' : '0',
      ).then(data => {
        if (data !== true && typeof data === 'string' && data !== '') {
          // Funcs.Notify(this.Term.Notify.warningTitle, data, "warning");
          this.notify({
            caption: Terms.Notify.warningTitle,
            type: 'warning',
            message: data,
          });
        }
      });
    },

    // 转换 @我 之类的关键字
    getConvertedFilterExpression() {
     return  FilterExpression( { FilterContent: JSON.stringify(this.FilterScheme) },
      this.getFields())
      return Funcs.GetFilterExpression(
        { FilterContent: JSON.stringify(this.FilterScheme) },
        this.getFields(),
      );
    },
  },

  expose: [
    // 子组件调用的
    'FiltersIsShow',
    'setUserPlan',
    'GetInitValueByScript',
    'GetFieldGroups',
    'FilterIsClassic',
    'FilterIsEasy',
    'FilterGroups',
    'ValuesGroups',
    'changeApply',
    'filterQuery',
    'queryApply',
    'clearQuery',
    'resetQuery',

    // 暴漏给低代码的属性
    'FieldsConfig',
    'FilterScheme',
    'FilterCurrScheme',
    'isStopApply',
    // 暴漏给低代码的方法
    'setFilters',
    'getFilters',
    'setFields',
    'getFields',
    'getValueByCode',
    'setValueByCode',
    'addFilterItem',
    'getFilterParas',
    'getDynamicFilter',
    'getFilterCodes',
    'getDependParas',
    'setApplyShow',
    'setApplyHide',
    'setFilterShow',
    'setFilterHide',
    'getSummaryFields',
    'getConvertedFilterExpression',
    'getFasDynamicFilter',
    'statisticalQuery',
    'quckFilterInstance',
    'getGroupByFilter',
    'querySummary',
    'getAdvanceFilter',
    'setQuickFilterFilters',
    'enableQuickFilter', 'clearQuckFilterFilters'
  ],
};
</script>

<style></style>
